package com.hinacom.pix.client;

import ca.uhn.hl7v2.DefaultHapiContext;
import ca.uhn.hl7v2.HL7Exception;
import ca.uhn.hl7v2.HapiContext;
import com.hinacom.pix.serviceproxy.PixClient;
import com.hinacom.pix.serviceproxy.ReceiveListener;
import com.hinacom.pix.tls.TLSChennel;
import org.apache.log4j.Logger;

import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;

/**
 * Created by fyu on 2016/8/31.
 */
public abstract class BaseClient {
    protected abstract String getHost();
    protected abstract int getPort();
    private static Logger logger = Logger.getLogger(BaseClient.class);

    public String sendMessage(String message) throws HL7Exception {

        // TLSChennel.registerHttps("pix");

        String host = this.getHost();
        int port = this.getPort();

        PixClient pixClient = new PixClient(host, port);
        StringBuilder sb = new StringBuilder();
        pixClient.setReceiveListener(new ReceiveListener() {
            @Override
            public void onReceive(String data) {
                sb.append(data);
            }
        });

        pixClient.closeSocket();
        InputStream msgInputStream = null;
        try {
            msgInputStream = new ByteArrayInputStream(message.getBytes("UTF-8"));
            pixClient.openSocket();
            pixClient.process(msgInputStream);
        } catch (FileNotFoundException e) {
            logger.error(e);
        } catch (Exception e) {
            logger.error(e);
        } finally {
            pixClient.closeSocket();
        }

        // remove the start and end identify code
        String response = sb.toString();
        if (response.startsWith("\u000b")) {
            response = response.substring(1);
        }

        if (response.endsWith("\u001c")) {
            response = response.substring(0, response.length() - 1);
        }
        return response;
    }
}
